<template>
    <view>
        <!-- pages/question_answer_post/question_answer_post.wxml -->
        <view class="weui-toptips weui-toptips_warn" v-if="showTopTips">{{ errorInfo }}</view>
        <view class="containView">
            <form @submit.stop.prevent="formSubmit">
                <input class="easyInput" name="subject" :value="title" placeholder="标题" :focus="true" @focus="inputFocus" @blur="bindBlur" @input="titleInput" />

                <block v-if="searchKeyChange && !toAddDetail">
                    <block v-for="(item, index) in searchResultList" :key="item.result">
                        <view class="searchCell" @tap="cellClick" :id="item.tid">
                            <view class="resultTitle">
                                <block v-for="(subjectItem, index1) in item.subjectArr" :key="subjectItem.subjectkey">
                                    <text :class="subjectItem == keyword ? 'resultkey' : ''">{{ subjectItem }}</text>
                                </block>
                            </view>
                            <view class="cell-info-left">
                                <view class="icon-item cell-tag">
                                    <image class="cell-icon" :src="minImgDoc + 're_tag.png'"></image>
                                    <view class="cell-icon-text">{{ item.typename ? item.typename : '分类' }}</view>
                                </view>
                                <view class="icon-item cell-recount">
                                    <image class="cell-icon" :src="minImgDoc + 're_dis.png'"></image>
                                    <view class="cell-icon-text">{{ item.replies }}个回答</view>
                                </view>
                            </view>
                        </view>
                    </block>
                    <view class="noMoreView" v-if="hasMore">没有更多了</view>
                </block>

                <block v-if="searchKeyChange && toAddDetail">
                    <picker class="classType" name="classType" mode="selector" :range="classTypeList" range-key="name" @change="classTypeChange" v-if="classTypeList">
                        <text :decode="true">{{ classTypeList[classIndex].name ? classTypeList[classIndex].name : '选分类' }}</text>
                    </picker>

                    <textarea class="weui-input detailText" v-if="!fullScreen" name="message" placeholder="问题描述" @blur="detailFinish" :focus="isText" maxlength="-1" />

                    <!-- 上传图片 start -->
                    <view class="attachmentContain" v-if="!isevaluate">
                        <view class="audio-playView" v-if="recording">
                            <image mode="widthFix" :src="minImgDoc + 'record_close.png'" class="record-close" @tap="clear"></image>
                            <view class="record-time">{{ formatedRecordTime }}</view>
                            <image class="record-icon" :src="minImgDoc + 'record_icon.png'"></image>
                            <view class="record-finish" @tap="stopRecord">完成</view>
                        </view>

                        <view class="playViewContain" v-if="audio">
                            <view class="audio-playView">
                                <image
                                    mode="widthFix"
                                    :src="is_play ? minImgDoc + 'audio_play.png' : minImgDoc + 'audio_paused.png'"
                                    class="audio-icon audio-play"
                                    @tap="audio_play"
                                ></image>
                                <view class="control-process">
                                    <text class="current-process">
                                        <block v-if="current_process.length > 0">
                                            {{ current_process }}
                                        </block>
                                        <block v-else>00:00</block>
                                    </text>
                                    <slider
                                        class="slider"
                                        @change="hanle_slider_change"
                                        @touchstart="handle_slider_move_start"
                                        @touchend="handle_slider_move_end"
                                        min="0"
                                        block-size="12"
                                        block-color="#6199fd"
                                        :max="slider_max"
                                        activeColor="#5abf39"
                                        backgroundColor="rgb(153,153,153,0.4)"
                                        :value="slider_value"
                                    />
                                    <text class="total-process">
                                        <block v-if="total_process.length > 0">
                                            {{ total_process }}
                                        </block>
                                        <block v-else>00:00</block>
                                    </text>
                                </view>
                            </view>
                            <image class="deleteA audioDele" :src="minImgDoc + 'att_delete.png'" :id="audio.aid" @tap="deleteAudio"></image>
                        </view>

                        <view class="uploader__files">
                            <block v-for="(image, index) in imageList" :key="image.aid">
                                <view class="uploader__file" :id="image.aid">
                                    <image class="uploader__img" :src="image.src" :data-src="image.src" @tap="previewImage"></image>
                                    <image class="deleteA" :src="minImgDoc + 'att_delete.png'" :id="image.aid" @tap="deleteImage"></image>
                                </view>
                            </block>
                            <view class="uploader_videoContain" v-if="video">
                                <view class="uploader__file" :id="image.aid">
                                    <video
                                        id="myVideo"
                                        class="uploader__video uploader__input"
                                        :controls="false"
                                        :show-fullscreen-btn="false"
                                        @play="playVideo"
                                        @fullscreenchange="fullScreenChange"
                                        :src="video.src"
                                    ></video>
                                    <image class="deleteA" :src="minImgDoc + 'att_delete.png'" :id="video.aid" @tap="deleteVideo"></image>
                                </view>
                            </view>
                            <image class="uploader__input" :src="minImgDoc + 'post_addimage.png'" @tap="chooseImage"></image>
                            <image class="uploader__input" :src="minImgDoc + 'post_addaudio.png'" @tap="chooseAudio"></image>
                            <image class="uploader__input" :src="minImgDoc + 'post_addvideo.png'" @tap="chooseVideo"></image>
                        </view>
                    </view>

                    <!-- 上传图片 end -->
                    <button class="postBtn" :disabled="postLock" type="primary" formType="submit">提问</button>
                </block>

                <block v-if="searchKeyChange && !toAddDetail">
                    <view class="addDetail" :disabled="postLock" type="primary" @tap.stop.prevent="addDetail" :style="'bottom:' + keyboardHeight + 'px'">添加详细描述</view>
                </block>
            </form>
        </view>
    </view>
</template>

<script>
// pages/question_answer_post/question_answer_post.js
const uploadFileUrl = require('../../config').uploadFileUrl;

const postInfoUrl = require('../../config').postInfoUrl;

const postThreadUrl = require('../../config').postThreadUrl;

const searchThreadUrl = require('../../config').searchThreadUrl;

const util = require('../../utils/util.js');

const datacheck = require('../../utils/datacheck.js');

const minImgDoc = require('../../config').minImgDoc;

var recordTimeInterval;
const app = getApp();
 // 附件分类

var fileCatalog = {
    image: 0,
    audio: 1,
    video: 2
};
export default {
    data() {
        return {
            minImgDoc: minImgDoc,
            searchKeyChange: false,
            toAddDetail: false,
            keyboardHeight: 0,
            title: '',
            keyword: '',
            page: 1,
            hasMore: true,
            recordTime: 0,
            recording: false,
            searchResultList: [],
            singleResultArr: [],
            imageList: [],
            fid: '',
            hasRecord: false,
            audioPrepareUrl: '',
            current_process: '',
            slider_value: '',
            total_process: '',
            slider_max: '',
            uploadhash: '',
            cityid: '',
            districtid: '',
            schoolid: '',

            classTypeList: {
                name: false
            },

            typeObj: '',

            audio: {
                aid: ''
            },

            video: {
                src: '',
                aid: ''
            },

            fullScreen: '',
            status: 0,
            formatedRecordTime: '',
            is_play: false,
            is_ended: false,
            is_moving_slider: false,
            classIndex: '',
            errorInfo: '',
            showTopTips: false,
            postLock: false,
            currentTab: 0,

            subjectItem: {
                subjectkey: ''
            },

            isText: false,
            isevaluate: '',

            image: {
                aid: '',
                src: ''
            }
        };
    },
    onReady() {
        this.videoContext = uni.createVideoContext('myVideo');
    },
    onHide: function () {
        if (this.recording) {
            this.recording= false;this.recordTime= 0;
            this.stopRecord();
        }
    },
    onUnload: function () {
        uni.setKeepScreenOn({
            keepScreenOn: false
        });
    },
    onLoad: function (options) {


        if (options.fid) {
            this.fid= options.fid;
        } // 语音

        this.recorderManager = uni.getRecorderManager();
        this.recorderManager.onError(function (res) {
            var errMsg = res.errMsg;

            if (errMsg.indexOf('auth deny') != -1) {
                // errMsg = "没有访问麦克风的权限"
                // wx.showToast({
                //   title: errMsg,
                //   icon: 'none'
                // })
            }
        });
        this.recorderManager.onStop(function (res) {
            this.hasRecord= true;
            uni.setKeepScreenOn({
                keepScreenOn: false
            });
            clearInterval(recordTimeInterval);
            var recordTime = Math.floor(res.duration / 1000);
            this.recordTime= recordTime;
            console.log(recordTime);

            if (this.recording) {
                this.audioPrepareUrl= res.tempFilePath;
                this.uploadFile(res.tempFilePath, fileCatalog.audio);
            }
        });
        this.innerAudioContext = uni.createInnerAudioContext();
        this.innerAudioContext.onTimeUpdate(() => {
            if (!this.is_moving_slider) {
                // 播放中
                this.current_process= util.formatTime(this.innerAudioContext.currentTime)
                    this.total_process= util.formatTime(this.innerAudioContext.duration)
                    this.slider_max= Math.floor(this.innerAudioContext.duration)

            }

            if (this.innerAudioContext.currentTime >= this.recordTime) {
                this.stopVoice();
            }
        });
        this.checkPost();
        this.keyword= '如何提高写作能力';
        var singleResultArr = this.getHilightStrArray('如何提高写作能力？使写作水平提高', this.keyword);
        this.singleResultArr= singleResultArr;
    },
    onPullDownRefresh: function () {},
    onReachBottom: function () {
        if (this.hasMore) {
            this.page++;
            this.searchThread();
        }
    },
    methods: {
        getHilightStrArray: function (str, key) {
            return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
        },

        checkPost() {
            app.globalData.apimanager
                .getRequest(postInfoUrl, {
                    fid: this.fid
                })
                .then((res) => {
                    if (res.Variables.swfconfig) {
                        this.setData({
                            uploadhash: res.Variables.swfconfig.hash,
                            cityid: res.Variables.member_city,
                            districtid: res.Variables.member_district,
                            schoolid: res.Variables.member_school
                        });
                    }

                    this.classTypeList= res.Variables.threadtypes.newtypes;this.typeObj= res.Variables.threadtypes.types;
                })
                .catch((res) => {});
        },

        searchThread() {
            var data = {
                subject: this.keyword,
                fid: this.fid,
                page: this.page,
                formhash: app.globalData.formhash
            };
            app.globalData.apimanager
                .getRequest(searchThreadUrl, data)
                .then((res) => {
                    if (res.Variables) {
                        var arr = res.Variables.thread;

                        for (let i = 0; i < arr.length; i++) {
                            let resultItem = arr[i];
                            var subjectArr = this.getHilightStrArray(resultItem.subject, this.keyword);
                            resultItem['subjectArr'] = subjectArr;
                        }

                        if (this.page > 1) {
                            arr = this.searchResultList.concat(arr);
                        }

                        this.searchResultList= arr;this.hasMore= true;
                    } else {
                        if (this.page == 1) {
                            this.searchResultList= [];
                        }

                        this.hasMore= false;
                    }
                })
                .catch((res) => {});
        },

        addDetail(e) {
            this.toAddDetail= true;
        },

        inputFocus(e) {
            this.keyboardHeight= e.detail.height;
        },

        bindBlur(e) {
            this.keyboardHeight= 0;
        },

        titleInput(e) {
            if (this.title != e.detail.value) {
                this.toAddDetail= false;

                if (e.detail.value) {
                    this.searchKeyChange= true;
                    this.page= 1;this.keyword= e.detail.value;
                    this.searchThread();
                } else {
                    this.searchKeyChange= false;
                }
            }

            this.title= e.detail.value;
        },

        chooseImage() {
            if (this.imageList.length == 9) {
                uni.showToast({
                    title: '最多上传9张图片',
                    icon: 'none'
                });
                return;
            }

            uni.chooseImage({
                count: 9 - this.imageList.length,

                success(res) {
                    console.log(res);

                    for (let key in res.tempFilePaths) {
                        let imageSrc = res.tempFilePaths[key];
                        this.uploadFile(imageSrc, fileCatalog.image);
                    }
                }
            });
        },

        uploadFile(uploadSrc, type) {
            var uploadUrl = uploadFileUrl + '&fid=' + this.fid;
            let uploadhash = this.uploadhash;
            let uid = app.globalData.uid;
            let postDic = {
                hash: uploadhash,
                uid: uid
            };
            uni.showLoading({
                title: '上传附件',
                icon: 'loading'
            });
            app.globalData.apimanager
                .uploadFile(uploadUrl, uploadSrc, 'Filedata', postDic)
                .then((res) => {
                    uni.hideLoading();
                    var result = datacheck.uploadStatusCheck(res);

                    if (result.success) {
                        uni.showToast({
                            title: '上传成功',
                            icon: 'success',
                            duration: 1000
                        });
                        let aid = result.data;

                        if (type == fileCatalog.image) {
                            var imageList = this.imageList;
                            console.log('图片');
                            let imgObj = {
                                aid: aid,
                                src: uploadSrc
                            };
                            imageList.push(imgObj);
                            this.imageList= imageList;
                        } else {
                            if (type == fileCatalog.audio) {
                                console.log('音频');
                                this.audioPrepareUrl= '';
                                var data = {
                                    aid: aid,
                                    src: uploadSrc
                                };
                                let recordTime = this.recordTime;
                                this.audio= data
                                    this.slider_max= Math.floor(recordTime)
                                    this.recording= false

                            } else {
                                if (type == fileCatalog.video) {
                                    var data = {
                                        aid: aid,
                                        src: uploadSrc
                                    };
                                    this.video= data;
                                }
                            }
                        }
                    } else {
                        uni.showModal({
                            content: result.data,
                            showCancel: false,
                            confirmText: '确定'
                        });
                    }
                })
                .catch((res) => {
                    uni.hideLoading();
                    uni.showModal({
                        content: '上传失败',
                        showCancel: false,
                        confirmText: '确定'
                    });
                });
        },

        playVideo() {
            this.videoContext.play();
            this.videoContext.requestFullScreen();
        },

        fullScreenChange(e) {
            console.log(e.detail);
            this.fullScreen= e.detail.fullScreen;
        },

        previewImage(e) {
            const current = e.target.dataset.src;
            var imageSrcArray = [];

            for (let i = 0; i < this.imageList.length; i++) {
                let item = this.imageList[i];
                imageSrcArray.push(item.src);
            }

            uni.previewImage({
                current,
                urls: imageSrcArray
            });
        },

        chooseAudio() {
            if (this.audio) {
                uni.showToast({
                    title: '最多上传一个语音',
                    icon: 'none'
                });
                return;
            }

            if (this.recording) {
                return;
            }

            this.startRecord();
        },

        chooseVideo() {
            uni.chooseVideo({
                camera: 'back',
                maxDuration: 60,

                success(res) {
                    this.uploadFile(res.tempFilePath, fileCatalog.video);
                }
            });
        },

        startRecord() {
            uni.authorize({
                scope: 'scope.record',

                success() {
                    console.log('录音授权成功'); //第一次成功授权后 状态切换为2

                    this.status= 2; // 用户已经同意小程序使用录音功能，后续调用 this.recordStart 接口不会弹窗询问

                    this.recordStartNow();
                },

                fail() {
                    uni.showModal({
                        title: '提示',
                        content: '您未授权录音，功能将无法使用',
                        showCancel: true,
                        confirmText: '授权',
                        confirmColor: '#52a2d8',
                        success: function (res) {
                            if (res.confirm) {
                                //确认则打开设置页面（重点）
                                uni.openSetting({
                                    success: (res) => {
                                        console.log(res.authSetting);

                                        if (!res.authSetting['scope.record']) {
                                            //未设置录音授权
                                            console.log('未设置录音授权');
                                            uni.showModal({
                                                title: '提示',
                                                content: '您未授权录音，功能将无法使用',
                                                showCancel: false,
                                                success: function (res) {}
                                            });
                                        } else {
                                            //第二次才成功授权
                                            this.status= 2;
                                            this.recordStartNow();
                                        }
                                    },
                                    fail: function () {
                                        console.log('授权设置录音失败');
                                    }
                                });
                            } else {
                                if (res.cancel) {
                                    console.log('cancel');
                                }
                            }
                        },
                        fail: function () {
                            console.log('openfail');
                        }
                    });
                }
            });
        },

        recordStartNow() {
            clearInterval(recordTimeInterval);
            this.setData({
                recording: true,
                recordTime: 0,
                formatedRecordTime: '00:00'
            });
            uni.setKeepScreenOn({
                keepScreenOn: true
            });
            recordTimeInterval = setInterval(function () {
                const recordTime = (this.recordTime += 1);
                this.setData({
                    formatedRecordTime: util.formatTime(this.recordTime),
                    recordTime
                });
            }, 1000);
            this.recorderManager.start({
                format: 'mp3',
                duration: 180000
            });
        },

        stopRecord() {
            clearInterval(recordTimeInterval);
            this.recorderManager.stop();

            if (this.audioPrepareUrl) {
                this.uploadFile(this.audioPrepareUrl, fileCatalog.audio);
            }
        },

        // 点击播放暂停
        audio_play: function () {
            if (this.is_play) {
                this.is_play= false;
                console.log('暂停');
                this.innerAudioContext.pause();
            } else {
                if (!this.is_play && this.is_ended) {
                    this.playVoice();
                    this.is_play= true;this.is_ended= false;
                } else {
                    if (!this.is_play) {
                        console.log('即将播放');
                        this.is_play= true;
                        this.playVoice();
                    }
                }
            }
        },

        // 拖动进度条，到指定位置
        hanle_slider_change(e) {
            const position = e.detail.value;
            this.seekCurrentAudio(position);
        },

        // 拖动进度条控件
        seekCurrentAudio(position) {
            this.innerAudioContext.seek(position);
            this.current_process= util.formatTime(position)
        },

        // 进度条滑动
        handle_slider_move_start() {
            this.is_moving_slider= true;
        },

        handle_slider_move_end() {
            this.is_moving_slider= false;
        },

        playVoice() {
            var src = this.audio.src;

            if (src == '') {
                return;
            }

            this.innerAudioContext.src = src;
            this.innerAudioContext.play();
        },

        stopVoice() {
            this.current_process= util.formatTime(0)
                this.is_play= false
            this.innerAudioContext.stop()
        },

        clear() {
            this.setData({
                is_play: false,
                hasRecord: false,
                recording: false,
                audio: null,
                formatedRecordTime: util.formatTime(0),
                recordTime: 0
            });
            this.stopRecord();
        },

        deleteVideo(e) {
            var aid = e.currentTarget.id;
            console.log(aid);
            this.video= null;
        },

        deleteImage(e) {
            var aid = e.currentTarget.id;
            var imageList = this.imageList;
            var index;

            for (let i = 0; i < imageList.length; i++) {
                let data = imageList[i];

                if (data.aid == aid) {
                    index = i;
                }
            }

            imageList.splice(index, 1);
            this.imageList= imageList;
            console.log(aid);
        },

        deleteAudio(e) {
            var aid = e.currentTarget.id;
            this.audio= null;
        },

        classTypeChange(e) {
            var classIndex = e.detail.value;
            console.log(classIndex);
            this.classIndex= classIndex;
        },

        formSubmit(e) {
            let msg = e.detail.value.message;
            let subject = e.detail.value.subject;
            let isError = false;
            let errStr = '';

            if (!subject) {
                isError = true;
                errStr = '请输入标题';
            }

            var postDic = {
                formhash: app.globalData.formhash,
                message: util.filterEmoji(msg),
                subject: subject,
                special: 3,
                // 悬赏
                rewardprice: 1,
                // 悬赏金钱
                cityid: this.cityid,
                districtid: this.districtid,
                schoolid: this.schoolid
            };

            if (this.classTypeList) {
                if (!e.detail.value.classType) {
                    isError = true;
                    errStr = '请选择提问类型';
                } else {
                    let typeIndex = parseInt(e.detail.value.classType);
                    let classObj = this.classTypeList[typeIndex];
                    postDic['typeid'] = classObj.typeid;
                }
            }

            if (isError) {
                this.errorInfo= errStr;this.showTopTips= true;
                setTimeout(function () {
                    this.showTopTips= false;
                }, 2000);
                return;
            }

            if (this.imageList.length > 0) {
                for (let i = 0; i < this.imageList.length; i++) {
                    let imgObj = this.imageList[i];
                    let aid = imgObj['aid'];
                    let attachKey = 'attachnew[' + aid + '][description]';
                    postDic[attachKey] = '';
                }
            }

            if (this.audio) {
                let attachKey = 'attachnew[' + this.audio.aid + '][description]';
                postDic[attachKey] = this.recordTime;
            }

            if (this.video) {
                let attachKey = 'attachnew[' + this.video.aid + '][description]';
                postDic[attachKey] = '';
            }

            uni.showLoading({
                title: '发布中...',
                icon: 'loading'
            });
            this.postLock= true;
            var url = postThreadUrl + '&fid=' + this.fid;
            app.globalData.apimanager
                .postRequest(url, postDic)
                .then((res) => {
                    uni.hideLoading();
                    this.postLock= false;

                    if (res.Message.messageval.indexOf('succeed') != -1 || res.Message.messageval.indexOf('success') != -1) {
                        let pages = getCurrentPages(); //获取当前页面

                        let prevPage = pages[pages.length - 2]; //获取上个页面

                        prevPage.setData({
                            currentTab: 1
                        });
                        prevPage.refreshRequest();
                        uni.navigateBack();
                        uni.showToast({
                            title: '发表成功',
                            icon: 'success',
                            mask: true,
                            duration: 3000
                        });
                    } else {
                        uni.showToast({
                            title: res.Message.messagestr,
                            icon: 'none'
                        });
                    }
                })
                .catch((res) => {
                    console.log(res);
                    uni.hideLoading();
                    this.postLock= false;
                    uni.showToast({
                        title: '出错了！',
                        icon: 'none'
                    });
                });
        },

        cellClick(e) {
            uni.navigateTo({
                url: '../question_answer_detail/question_answer_detail?tid=' + e.currentTarget.id
            });
        },

        detailFinish() {
            console.log('占位：函数 detailFinish 未声明');
        }
    }
};
</script>
<style>
@import './question_answer_post.css';
</style>
